package cc.rengu.igas.cops.common.util;

import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ShaUtil {
    /* 算法常量： SHA1 */
    private static final String ALGORITHM_SHA1 = "SHA-1";
    /* 算法常量： SHA256 */
    private static final String ALGORITHM_SHA256 = "SHA-256";
    /* 算法常量：SHA1withRSA */
    private static final String BC_PROV_ALGORITHM_SHA1RSA = "SHA1withRSA";
    /* 算法常量：SHA256withRSA */
    private static final String BC_PROV_ALGORITHM_SHA256RSA = "SHA256withRSA";


    /**
     * SHA散列加签，不送默认SHA-256
     *
     * @param encType
     * @param blockString
     * @return base64加密字符串
     */
    public static String generateSignString(String encType, String... blockString) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            for (String signBlock : blockString) {
                stringBuilder.append(signBlock);
            }
            String signData = stringBuilder.toString();
            MessageDigest mdInst = MessageDigest.getInstance((null == encType) ? ALGORITHM_SHA256 : encType);
            mdInst.update(signData.getBytes());
            return Base64.encodeBase64String(mdInst.digest());
        } catch (NoSuchAlgorithmException e) {

            return null;
        }
    }

    /**
     * 校验SHA-256加签串
     *
     * @param verifyData  校验加签域
     * @param blockString 原始加签数据
     * @return true-成功，false-失败
     */
    public static boolean verifySignString(String verifyData, String encType, String... blockString) {
        String signData = generateSignString(encType, blockString);
        if (null == signData) {
            return false;
        } else {
            return verifyData.equalsIgnoreCase(signData);
        }
    }

    /**
     * sha256 消息摘要
     *
     * @param message
     * @return
     */
    public static byte[] sha256(byte[] message) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(ALGORITHM_SHA256);
            md.reset();
            md.update(message);
            return md.digest();
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * sha1 消息摘要
     *
     * @param message
     * @return
     */
    public static byte[] sha1(byte[] message) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(ALGORITHM_SHA1);
            md.reset();
            md.update(message);
            return md.digest();
        } catch (Exception e) {

        }
        return null;
    }
}